package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.service.MemberService;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.*;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.LikeEnum;
import com.kly.user.enums.WLMType;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.serviceImpl.traffic.likeback.LikebackTrafficHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * LIKE BACK 下发
 */
@Component
public class LikeBackIssueTask {
    private static Log logger = LogFactory.getLog(LikeBackIssueTask.class);

    @Autowired
    private UserDao userDao;

    @Resource
    UserWlmDao userWlmDao;

    @Resource
    UserWlmLogDao userWlmLogDao;

    @Resource
    AsyncEventBus pushEventBus;

    @Autowired
    IssueConfigDao issueConfigDao;

    @Resource
    private IssueUserDao issueUserDao;

    @Resource
    private IssueLbRecordDao issueLbRecordDao;

    @Resource
    private UserBehaviorGpsDao userBehaviorGpsDao;

    @Resource
    private MemberService memberService;

    @Resource
    private UserMsgSendTotalDao userMsgSendTotalDao;

    @Resource
    private CustomersUserDao customersUserDao;

    @NacosValue(value = "${master.task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    @NacosValue(value = "${task.job.like.back.version:1}", autoRefreshed = true)
    private Integer taskJobLikeBackVersion;

    @NacosValue(value = "${meboo.homepage.new.policy.show.detail:false}", autoRefreshed = true)
    private boolean showHomepageNewPolicyVersionDetail;

    private String localIP = NetUtil.getLocalhostStr();

    // 流量池测试开关
    @NacosValue(value = "${issue.user.pool.test:false}", autoRefreshed = true)
    private boolean issueUserPoolTest;
    // 流量池测试用户
    @NacosValue(value = "${issue.user.pool.test.userCode}", autoRefreshed = true)
    private String issueUserPoolTestUserCode;

    @Scheduled(fixedDelay = 30000)
    public void execute() {
        logger.info("==likebackV5 下发 任务开始 ==");
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============likebackV5 NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        IssueConfigEntity issueConfigEntity = issueConfigDao.queryIssueConfig(2);
        if (issueConfigEntity != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -2);
            Date date = calendar.getTime();
            // 分页查询2天内活跃的用户
            int count = userDao.getRegisterDateUserCount(String.valueOf(date.getTime()));
            logger.info("==likebackV5 最近2天活跃的用户数==,count:{}", count);
            if (count < 0) {
                logger.info("==likebackV5 最近2天活跃的用户数 小于0 任务终止==,count:{}", count);
                return;
            }

            logger.info("==likebackV5 开始执行likeback==");
            int pageSize = (count / 100) + 1;
            for (int i = 0; i < pageSize; i++) {
                logger.info("==likebackV5 开始执行likeback 获取分页，页数:{}==", i + 1);
                List<UserEntity> userEntityList = userDao.getRegisterDateUserLimit(String.valueOf(date.getTime()), i);
                logger.info("==likebackV5 开始执行likeback 获取分页，页数:{},数量:{}==", i + 1, userEntityList.size());
                try {
                    if (CollectionUtils.isEmpty(userEntityList)) {
                        logger.info("==likebackV5 开始执行likeback 执行完成，该页已经没有数据，页数:{}==", i + 1);
                        break;
                    }

                    for (UserEntity userEntity : userEntityList) {
                        logger.info("==likebackV5 开始执行likeback 给用户:{} 下发likeback==", userEntity.getUserCode());
                        dealCondition(issueConfigEntity, userEntity);
                    }
                } catch (Exception e) {
                    logger.error("==likebackV5 执行异常，页数:{}==", i + 1, e);
                }

                if (userEntityList.size() != 100) {
                    break;
                }

            }


        }
    }

    /**
     * 条件判断处理
     *
     * @param issueConfigEntity
     * @param userEntity
     */
    private void dealCondition(IssueConfigEntity issueConfigEntity, UserEntity userEntity) {
        LikebackTrafficHandler.likeBackBaseMap.get(userEntity.getAppCode()).dealCondition(issueConfigEntity, userEntity);
    }


    public void doLikeBack(String userCode, String toUserCode, String app) {
        UserWlmEntity relation = userWlmDao.getRelation(userCode, toUserCode);
        relation.setWlmType(LikeEnum.LIKE_EACH_OTHER.getType());
        if (relation.getConnectType() == 0) {
            relation.setConnectType(WLMType.LIKEBACK.getCode());
        }
        relation.setContactTime(new Date());
        relation.setLikesBackTime(new Date());
        userWlmDao.updateByPrimaryKey(relation);

        //新增likeback记录
        UserWlmEntity modelLikesBackRecord = new UserWlmEntity();
        modelLikesBackRecord.setLikesBackTime(new Date());
        modelLikesBackRecord.setContactTime(new Date());
        modelLikesBackRecord.setLikesTime(new Date());
        modelLikesBackRecord.setUserCode(toUserCode);
        modelLikesBackRecord.setUserCodeWlm(userCode);
        modelLikesBackRecord.setWlmType(LikeEnum.LIKE_EACH_OTHER.getType());
        modelLikesBackRecord.setConnectType(WLMType.LIKEBACK.getCode());
        userWlmDao.insert(modelLikesBackRecord);

        userWlmLogDao.addWlmLog(modelLikesBackRecord);

        addLikeBackRecord(userCode, toUserCode);

        try {
            pushNewMatchMessage(toUserCode, userCode, AppEnum.getEnumByUserAppFlat(app));
        } catch (Exception e) {
            logger.info("pushNewMatchMessage error: " + e.getMessage());
        }
    }


    /**
     * 添加记录
     *
     * @param userCode
     * @param toUserCode
     */
    private void addLikeBackRecord(String userCode, String toUserCode) {
        IssueLbRecordEntity issueLbRecordEntity = new IssueLbRecordEntity();
        issueLbRecordEntity.setUserCode(userCode);
        issueLbRecordEntity.setModelUserCode(toUserCode);
        UserEntity userEntity = userDao.selectByUserCode(toUserCode);
        issueLbRecordEntity.setOnlineStatus(userEntity.getOnline());
        issueLbRecordDao.insert(issueLbRecordEntity);
    }

    private void pushNewMatchMessage(String fromUserCode, String toUserCode, AppEnum appEnum) {
        pushEventBus.post(buildEvent(fromUserCode, toUserCode, appEnum));
    }

    private Event buildEvent(String fromUserCode, String toUserCode, AppEnum appEnum) {
        Map<String, Integer> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.MATCHED_PUSH.getId());
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUserCode).toUserCode(toUserCode).app(appEnum).content(JSONObject.toJSONString(params)).build();
    }

    /**
     * 判断当日是否有深度会话
     *
     * @param userCode
     * @return
     */
    private boolean ifConversationSure(String userCode) {
        boolean result = false;
        int count = userMsgSendTotalDao.getUserSendMsgCount(userCode);
        if (count > 0) {
            result = true;
        }
        return result;
    }


    // 5s轮询
    //过滤非model用户
    //过滤已举报过的用户
    //过滤已拉黑用户
    //过滤已建联用户
    //符合24h我like过的在线cm
    //配置表 用户like back变量(0.00) like back数量 min第一个参数 第二个参数  h参数  时间(time)

    //计算公式是否>0  今日用户like的次数*60%-今日like back次数＞0
    //今日下发次数小于3
    //判断用户是否在线 用户在线 距离上次下发时间 是否大于等于（1+今日下发like back次数*1）min
    //用户当日是否启动过app 启动过 距离上次下发时间 是否大于(今日下发like back次数*0.5)
    //用户未启动过app  当前时间>配置的时间 距离上次下发的时间大于 （今日下发like back次数*0.5）h

//DateUtil.between(DateUtil.date(), user.getGmtCreate(), DateUnit.MINUTE);

}
